import Vue from "vue";
import moment from 'moment';
import request from "@/utils/request";
/** 引入message弹窗 */
import { MessageBox, Message } from 'element-ui'

export default {
  calculControlWidth(length) {
    let span = 8
    if (length == 1) {
        span = 8
    } else if (length == 2) {
        span = 12
    } else if (length == 3) {
        span = 24
    } else {
        span = 8
    }
    return span;
  },
  getWeek (dateTime) {
    let temptTime = moment(dateTime)
    //周几
    let weekday = temptTime.day()
    let dateList = []
    for(let days=weekday; days>0; days--) {
      let weekday = moment(dateTime)
      dateList.push(weekday.subtract(days,'d').get('date'))
    }
    for(let days=0; days<7-weekday; days++) {
      let weekday = moment(dateTime)
      dateList.push(weekday.add(days,'d').get('date'))
    }

    let theSaturday = temptTime.get('date') + (6 - temptTime.day()); 
    const toWeek = Math.ceil(theSaturday / 7)
    const weekData = {toWeek, dateList}
    return weekData
  },
  isEmpty: function (val) {
    if (val === undefined || val === null || val === "") {
      return true;
    } else {
      return false;
    }
  },
  commentui(that, ui, mountdiv, rules) {
    that.rules = rules;
    that.$nextTick(() => {
      // 用v-if解决new组件后，不能自动销毁
      ui = "<div class='page-controlstyle' v-if='destroystate'>" + ui + "</div>";
      //解析表单元素
      let startIndex = 0;
      startIndex = ui.indexOf("v-model=\"");
      startIndex = startIndex + 9;
      while (startIndex > 0) {
        let endIndex = ui.indexOf("\"", startIndex);
        let propName = ui.substring(startIndex, endIndex);
        //为组件添加属性名称，便于接收事件信息
        ui = ui.slice(0, endIndex + 1) + " :propName=\"'" + propName.substring(3) + "'\"" + ui.slice(endIndex + 1);
        //下一个
        startIndex = endIndex;
        startIndex = ui.indexOf("v-model=\"", startIndex);
        if (startIndex > 0) {
          startIndex = startIndex + 9;
        }
      }
      

      var MyComponent = Vue.extend({
        template: ui,
        store: that.$store,
        data() {
          return that._data;
        }
      });
      // 必须new后挂载到元素上，不然会覆盖之前的动态组件
      mountdiv = this.isEmpty(mountdiv) ? "uicontent" : mountdiv;
      // 如果在界面渲染和加载则可以用下面语法挂载制定div的id
      // new MyComponent().$mount(mountdiv);
      let divui = new MyComponent().$mount();
      that.$refs[mountdiv].innerHTML = '';
      that.$refs[mountdiv].appendChild(divui.$el);
    })
  },
  loadDynamicUI(that, code, mountdiv) {
    let self = this;
    let cacheKey = "dynamicUI_" + code;
    let data = window.localStorage.getItem(cacheKey);
    if (data) {
      let jsonData = JSON.parse(data);
      let rules = [];
      if (jsonData.checkRules) {
        rules = JSON.parse(jsonData.checkRules.replace(/\r\n/g,'').replace(/\n/g,''));
      }
      
      self.commentui(that, jsonData.pageCode, mountdiv, rules);
    } else {
      return request.post("page/getDynamicPage", {code: code}).then( res => {
        if (res.data && res.data.pageCode) {
          let rules = [];
          if (res.data.checkRules) {
            //保存检查规则
            rules = JSON.parse(res.data.checkRules.replace(/\r\n/g,'').replace(/\n/g,''));
          }
          let pageContent = res.data.pageCode;
          if (!self.isEmpty(pageContent)) {
            window.localStorage.setItem(cacheKey, JSON.stringify(res.data));
          }
          self.commentui(that, pageContent, mountdiv, rules);
        } else {
          console.log("组件加载失败");
        }
      });
    }
  },
  /**
 * 删除等再次确认提示
 * @param {string} message  提示信息
 * @returns 
 */
  confirm(message = '此操作将永久删除该数据, 是否继续?') {
    return new Promise((resolve, reject) => {
        MessageBox.confirm(message,'温馨提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }).then(() => {
            resolve(true)
        }).catch(() => {
            reject(false)
        })
    })
  },
  andCondition(fieldName, value, logic='and', data=[]) {
    let condition = [{componentName: null, defaultValue: null, fieldName, fixCondition: false, id: null,
    leftParenthesis: null, logic, name: null, opCondition: '=', rightParenthesis: null, value}]
    condition = [...condition,...data]
    return condition
  },
  addWhere(conditionList, column, val, op, logic) {
    if (!logic) {
      logic = "and";
    }
    if (!op) {
      op = "=";
    }
    conditionList.push({
      logic: logic,
      leftParenthesis: "",
      fieldName: column,
      opCondition: op,
      rightParenthesis: "",
      value: val
    })
  },
  addGroupWhere(conditionList, logic, leftP, column, opCondition, val, rightP) {
    conditionList.push({
      logic: logic,
      leftParenthesis: leftP,
      fieldName: column,
      opCondition: opCondition,
      rightParenthesis: rightP,
      value: val
    })
  },
  addOrWhere(conditionList, column, val) {
    conditionList.push({
      logic: "or",
      leftParenthesis: "",
      fieldName: column,
      opCondition: "=",
      rightParenthesis: "",
      value: val
    })
  },
  showResultMsg(res) {
    if (200 == res.code) {
      Message.success(res.msg);
    } else {
      Message.error(res.msg);
    }
  },
  cartesian(arrays) {
    return arrays.reduce((accumulator, currentArray) => {
      return accumulator.flatMap((acc) => {
        return currentArray.map((curr) => {
          return Array.isArray(acc) ? [...acc, curr] : [acc, curr];
        });
      });
    });
  },
  lineToHump(str) {
    return str.replace(/_([a-z])/g, function (match, letter) {
      return letter.toUpperCase();
    });
  },

  convRules(listCheckes) {
    let result = {};
    for (let item of listCheckes) {
      let methods = item.checkMethod.split(",");
      let msg = item.msg;
      let rules = [];
      for (let check of methods) {
        if ("required" == check) {
          rules.push({ required: true, message: '请输入' + msg, trigger: 'blur' })
        } else if ("rangLength" == check) {
          rules.push({ min: Number(item.minLength), max: Number(item.maxLength), message: '长度在3到5个字符', trigger: 'blur'})
        } else if ("maxLength" == check) {
          rules.push({ max: Number(item.maxLength), message: '长度最多' + item.maxLength + '个字符', trigger: 'blur'})
        
        } else if ("minLength" == check) {
          rules.push({ min: Number(item.minLength), message: '长度最少' + item.minLength + '个字符', trigger: 'blur'})
        }
      }
      let propName = this.lineToHump(item.columnName)
      result[propName] = rules;
    }
    return result;
  },
  newUUID() {
    // 生成 8 位的随机字符串
    const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    // 使用 4 个随机字符串生成 32 位的十六进制数字
    return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
  },
  /**
   * 取得年月日的数字形式，用于生成条形码前缀
   */
  getNumDate() {
    let now = new Date();
    let year = now.getFullYear();
    year = year % 100;
    if (year < 10) {
      year = "0" + year;
    }
    let month = now.getMonth() + 1;
    if (month < 10) {
      month = "0" + month;
    }
    let day = now.getDate();
    if (day < 10) {
      day = "0" + day;
    }
    return year + "" + month + "" + day;
  }
}